package com.li.test.model6;

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import org.springframework.amqp.rabbit.connection.ConnectionFactory;

/**
 - 消息队列的配置类
 */
@Configuration
public class RabbitConfigModel6 {
    /**
     * 修改RabbitTemplate对象的配置
     */
    @Bean
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
        // 开启消息强制投递
        rabbitTemplate.setMandatory(true);
        // 消息到达交换机的确认回调
        rabbitTemplate.setConfirmCallback((correlationData, ack, cause) -> {
            System.out.println("消息数据：" + correlationData);
            if (ack) {
                System.out.println("消息已到达交换机");
            } else {
                System.out.println("消息未到达交换机，原因是：" + cause);
            }
        });
        // 消息回退：消息无法从交换机路由到队列
        rabbitTemplate.setReturnsCallback(returned -> {
            System.out.println("消息未达到，队列");
            System.out.println("消息内容：" + returned.getMessage());
            System.out.println("响应码：" + returned.getReplyCode());
            System.out.println("响应文本：" + returned.getReplyText());
            System.out.println("交换机：" + returned.getExchange());
            System.out.println("路由键：" + returned.getRoutingKey());
        });


        return rabbitTemplate;
    }

    @Bean
    public Queue confirmQueue1() {

        return new Queue("confirm.direct.queue1");
    }

    @Bean
    public DirectExchange confirmExchange() {
        return new DirectExchange("confirm.direct.exchange");
    }

    @Bean
    public Binding confirmDirectBinding1(Queue confirmQueue1, DirectExchange confirmExchange) {
        return BindingBuilder.bind(confirmQueue1).to(confirmExchange).with("sss");
    }





    /**
     * 消息序列化成JSON字符串
     */
//    @Bean
//    public MessageConverter messageConverter() {
//        return new Jackson2JsonMessageConverter();
//    }
}